package com.sjx.jtt809.server.pojo;

import com.sjx.jtt809.server.pojo.command.*;
import com.sjx.jtt809.server.util.ConstantJtt809Util;
import io.netty.buffer.ByteBuf;

import java.util.HashMap;
import java.util.Map;

/**
 * 响应类创建工厂
 */
public class ResponseFactory {

    private static Map<Integer, Class<? extends Response>> responseMap = new HashMap<Integer, Class<? extends Response>>();

    /**
     * 业务数据类型与bean对应的map集合
     */
    static {
        responseMap.put(ConstantJtt809Util.UP_CONNECT_REQ, ResponseJtt809_0x1001.class);
        responseMap.put(ConstantJtt809Util.UP_LINKETEST_REQ, ResponseJtt809_0x1005.class);
        responseMap.put(ConstantJtt809Util.DOWN_CONNECT_RSP, ResponseJtt809_0x9002.class);
        responseMap.put(ConstantJtt809Util.DOWN_LINKTEST_RSP, ResponseJtt809_0x9006.class);
        responseMap.put(ConstantJtt809Util.UP_EXG_MSG_REAL_LOCATION, ResponseJtt809_0x1202.class);
    }

    /**
     * 创建响应数据包
     *
     * @param msgId 业务数据类型
     * @param buf   数据包
     * @return
     */
    public static Response createResponse(int msgId, ByteBuf buf) {

        // 根据业务获取响应类
        Class<? extends Response> cls = null;

        switch (msgId) {
            case ConstantJtt809Util.UP_EXG_MSG:
                // 获取子业务类型
                int dataType = buf.getUnsignedShort(ConstantJtt809Util.DATA_TYPE_INDEX_OF_PACKAGE);
                cls = responseMap.get(dataType);
                break;
            default:
                cls = responseMap.get(msgId);
        }

        if (cls == null) {
            throw new RuntimeException("不支持的应答数据");
        }

        try {
            Response response = cls.newInstance();
            response.decode(buf);

            return response;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

}
